import threading
import socket
import time


class SnakeSock:
    """
    1. send和recv这两个方法都需要一直执行下去。
    """
    def __init__(self):
        # self.IP = '<broadcast>'
        self.IP = '255.255.255.255'
        self.PORT = 8888
        self.unicast_ip = None
        self.singgle_port = 8008

        self.ADDRESS = (self.IP, self.PORT)
        self.broadcast_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.broadcast_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.broadcast_sock.bind(self.ADDRESS)
        self.unicast_sock = socket.socket(type=socket.SOCK_DGRAM)

        self.id = str(time.time())              # 作为一台主机唯一的标识，用来区分IP是自己还是其他主机。
        self.state = None

        self.broadcast_send = threading.Thread(target=self.send)
        self.broadcast_recv = threading.Thread(target=self.recv)
        self.unicast_recv = threading.Thread(target=self.unicast_recv)
        # self.broadcast_send.start()
        self.broadcast_recv.start()

    def send(self):
        """"
        1.发送自己每走一步的位置给服务器。
        2.需要加锁。
        3.如果是服务器需要在一定时间内将所有数据发送给客户端。
        """
        print('a send')
        i = 0
        while 1:
            msg = 'a' + str(i) + ',' + self.id + ',' + str(self.state)
            self.broadcast_sock.sendto(msg.encode(), self.ADDRESS)
            i += 1
            time.sleep(1)

    def recv(self):
        """
        1.从客户端接收每一步的位置。
        2.需要加锁。
        """
        print(self.id)
        while 1:
            data, addr = self.broadcast_sock.recvfrom(1024)
            print('255 : ', data, addr)
            # datas = data.decode().rsplit(',')
            # if len(datas) > 1:
            #     if datas[1] == self.id and self.unicast_ip is None:
            #         # print('==')
            #         self.unicast_ip = addr[0]
            #         self.unicast_sock.bind(addr)
            #         self.unicast_recv.start()
            #     elif datas[1] != self.id:
            #         # print('!=')
            #         add = (addr[0], self.singgle_port)
            #         print('1', data, add)
            #         self.unicast_sock.sendto('a'.encode(), add)
            #         print('unicast')

    def unicast_recv(self):
        while 1:
            data, addr = self.unicast_sock.recvfrom(1024)
            print('unicast', data, addr)

    pass


s = SnakeSock()